package me.shurufa.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.adapter.BookCommentNewAdapter;
import me.shurufa.adapter.BookCommentNewMeAdapter;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.model.Book;
import me.shurufa.bean.BookComment;
import me.shurufa.model.BookCommentListResponse;
import me.shurufa.model.BookListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.colordialog.ColorDialog;
import me.shurufa.widget.commentbar.SendCommentBar;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 我收藏的某书中的所有书评Fragment
 */
public class MyCollectBookCommentFragment extends BaseListFragment implements View.OnClickListener {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.scb_comment_bar)
    SendCommentBar scb_comment_bar;

    ArrayList<BookComment> dataList;
    private BookCommentNewAdapter mCommentAdapter;
    private BookCommentNewMeAdapter mCommentMeAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;
    private Book header;
    private boolean mTypeMe;
    private int mWhereFrom;
    private long bookId;
    private String mBookname;
    private String pageFrom = "";
    private Handler mHandler = new Handler();

    private int mBaseBottomHeight; // 用于弹出键盘列表位移
    private int mKeyboardSize;
    private View mRootView;
    private boolean mIsOpenKeyborad;
    private boolean mIsLastPos; // 点击的是否是最后一个

    public static MyCollectBookCommentFragment newInstance(long bookId, String bookname, int whereFrom) {
        MyCollectBookCommentFragment fragment = new MyCollectBookCommentFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        args.putInt(Constants.ARG_FROM_WHERE, whereFrom);
        args.putString(Constants.ARG_BOOK_TITLE, bookname);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
            mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
            mBookname = getArguments().getString(Constants.ARG_BOOK_TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_mycollect_comment_list_new, container, false);
        ButterKnife.bind(this, mRootView);
        return mRootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();
        dataList = new ArrayList<BookComment>();

        mCommentAdapter = new BookCommentNewAdapter(getActivity(), mBookname, dataList, mWhereFrom);
        mCommentMeAdapter = new BookCommentNewMeAdapter(getActivity(), mBookname, dataList, mWhereFrom);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mCommentAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        //setLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.addOnScrollListener(mOnScrollListener);

        initListener();

    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(false);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

            if (scb_comment_bar != null && scb_comment_bar.getVisibility() == View.VISIBLE) {
                scb_comment_bar.setVisibility(View.GONE);
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, BookListResponse.class);
    }

    @Override
    protected String cacheKey() {
        return "shelves_book";
    }

//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh != null && ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage = 1;
        pageFrom = "";
        loadData(true);
    }

    private void onRefresh(boolean isChangedTab) {
        if (isChangedTab) {
            mCommentAdapter.clear();
        }
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 50);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(false);
        }
    };


    protected void loadData(final boolean pulldown) {
        final String lastItemId = dataList.size() == 0 ? "0" : dataList.get(dataList.size() - 1).id + "";

        if (!NetworkUtils.isNetAvailable(getActivity())) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        } else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<BookCommentListResponse>(BookCommentListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("bookId", bookId);
                    params.put("pageFrom", pulldown ? "" : (pageFrom == null ? "" : pageFrom));
                    params.put("pageSize", Constants.PAGE_REQUEST_COUNT);
                    params.put("pageDirection", Constants.DESC);
                    if (Global.currentUser != null) {
                        params.put("userId", Global.currentUser.id);
                    }

                    return HttpUtil.post(API.GET_COLLECT_BOOKCOMMENT_BY_USER_BOOK, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }

                @Override
                protected void onSuccess(BookCommentListResponse result) {
                    try {
                        pageFrom = result.page;
                        //没有更多数据 不能加载更多
                        if (result.data == null || result.data.length == 0) {//|| result.data.books.length == 0) {
                            hasMore = false;
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                            hasMore = true;
                            mPage++;
                            bindData(result, pulldown);
                        }
                    } catch (Exception e) {
                        Utils.showToast(R.string.sys_err);
                    }
                }
            }.start();
        }
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX, 0);
                EventBus.getDefault().post(intent);
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction() == Constants.ACTION_SHELVES_FAVOURITE) {
        } else if (intent.getAction() == Constants.ACTION_BOOKSHELVES_REFRESH
                || intent.getAction() == Constants.ACTION_ADD_DIGEST_COMPLETE) {
            refresh();
        }

        if (intent.getAction() == Constants.EVENT_SEND_BOOK_COMMENT) {
            BookComment bookComment = (BookComment) intent.getSerializableExtra(Constants.EVENT_SEND_BOOK_COMMENT);
            dataList.add(0, bookComment);
            mCommentAdapter.notifyDataSetChanged();
            mCommentMeAdapter.notifyDataSetChanged();
        }

        // 修改书评
        if (intent.getAction() == Constants.EVENT_MODIFY_BOOK_COMMENT) {
            int position = intent.getIntExtra(Constants.ARG_MODIFY_POSITION, -1);
            String content = intent.getStringExtra(Constants.ARG_COMMENT_CONTENT);
            if (position < 0) {
                return;
            }
            BookComment bookComment = dataList.get(position);
            bookComment.content = (content);
            mCommentMeAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        BookCommentListResponse resp = (BookCommentListResponse) response;

        // 我的
        if (mTypeMe) {
            if (!handleLoginClick()) {
                return;
            }
            if (isNew) {
                mCommentMeAdapter.clear();
                mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mCommentMeAdapter);
                recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
            }
            mCommentMeAdapter.append(resp.data);
            mCommentMeAdapter.notifyDataSetChanged();
            setSelectToTop();
            return;
        }

        // 其他

        if (isNew) {
            mCommentAdapter.clear();
            mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mCommentAdapter);
            recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        }
        mCommentAdapter.append(resp.data);
        mCommentAdapter.notifyDataSetChanged();
        setSelectToTop();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    /**
     * @param currentIndex
     * @return 获得请求的URL
     */
    private String getReqUrlByIndex(int currentIndex) {
        switch (currentIndex) {
            // 最赞
            case 0:
                return API.GET_PRAISE_BOOK_COMMENT;
            // 时间
            case 1:
                return API.GET_RECENT_OF_BOOK_COMMENT;
            // 只显示我的
            case 2:
                return API.GET_SELF_BOOK_COMMENT;
            default:
                return API.GET_PRAISE_BOOK_COMMENT;
        }
    }

    private void initListener() {
        recyclerView.addOnScrollListener(mOnScrollListener);

        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                mRootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = mRootView.getRootView().getHeight();
                int heightDifference = screenHeight - (r.bottom - r.top);

                heightDifference -= r.top;
                // 过滤已经展开
                if (!mIsOpenKeyborad) {
                    return;
                }

                if (heightDifference >= mKeyboardSize) {
                    mKeyboardSize = heightDifference;
                    // 获得屏幕高度
                    WindowManager wm = getActivity().getWindowManager();
                    int screenHeightReal = wm.getDefaultDisplay().getHeight();

                    // 获得点击控件的所在屏幕的高度(底部为准) mBaseBottomHeight
                    // 计算 1. 获得键盘顶部 和 item底部的偏移量
                    int keyboardTopHeightInParent = screenHeightReal - heightDifference;
                    int offset = - (keyboardTopHeightInParent - scb_comment_bar.getHeight() - mBaseBottomHeight);

                    // 如果点击是最后一个并且差值是负值(即还需要向下面滚，则自动过滤)
                    if (mIsLastPos && offset < 0) {
                        return;
                    }
                    recyclerView.scrollBy(0, offset);
                }
            }
        });

        /**
         * 触摸关闭评论条
         */
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //隐藏键盘
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    scb_comment_bar.setVisibility(View.GONE);
                    mIsOpenKeyborad = false;
                    Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                }
                return false;
            }
        });


        // 评论点击按钮监听
        /*mCommentAdapter.setOnSocialBarClickListener(new BookCommentNewAdapter.OnSocialBarClickListener() {
            @Override
            public void onCommentClick(final View v, final int position, BookComment comment) {
                scb_comment_bar.setBookComment(comment);
                scb_comment_bar.setVisibility(View.VISIBLE);
                scb_comment_bar.requestFocus();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int location[] = new int[2];
                        ((LinearLayout) v.getParent().getParent()).getLocationOnScreen(location);
                        mBaseBottomHeight = location[1] + ((LinearLayout) v.getParent().getParent()).getHeight();
                        mIsOpenKeyborad = true;
                        mIsLastPos = (mCommentMeAdapter.getItemCount() == position + 1);
                        Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
                    }
                }, 100);
            }

            @Override
            public void onReplyCommentClick(final View v, final int parentPosition, int childPosition, BookComment comment) {
                // 发送对评论的回复
                if (!Utils.isNullForList(comment.getComments())) {
                    NewComment replyComment = comment.getComments().get(childPosition);
                    scb_comment_bar.setBookComment(null);
                    scb_comment_bar.setBookCommentReplyComment(comment, replyComment);
                    scb_comment_bar.setVisibility(View.VISIBLE);
                    scb_comment_bar.requestFocus();
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int location[] = new int[2];
                        ((RelativeLayout) v.getParent().getParent()).getLocationOnScreen(location);
                        mBaseBottomHeight = location[1] + ((RelativeLayout) v.getParent().getParent()).getHeight();
                        mIsOpenKeyborad = true;
                        mIsLastPos = (mCommentMeAdapter.getItemCount() == parentPosition + 1);
                        Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
                    }
                }, 100);
            }

            @Override
            public void onPraiseClick(boolean prePraise, BookComment comment) {
                if (prePraise) {
                    reqPraise(comment);
                } else {
                    reqCancelPraise(comment);
                }
            }

            @Override
            public void onCollectClick(boolean preCollect, BookComment comment) {
                if (preCollect) {
                    reqCollect(comment);
                } else {
                    reqCancelCollect(comment);
                }
            }
        });*/

        /*mCommentMeAdapter.setOnMenuBarClickListener(new BookCommentNewMeAdapter.OnMenuBarClickListener() {

            @Override
            public void onPraiseClick(boolean prePraise, BookComment comment) {
                if (prePraise) {
                    reqPraise(comment);
                } else {
                    reqCancelPraise(comment);
                }
            }

            @Override
            public void onShare(BookComment bookComment) {
                Intent in = new Intent(getActivity(), ShareEditActivity.class);
                ShareEditActivity.initArguments(in, mBookname, null, bookComment);
                getActivity().startActivity(in);
            }

            @Override
            public void onReplyCommentClick(View v, final int parentPosition, int childPosition, BookComment comment) {
                // 发送对评论的回复
                if (!Utils.isNullForList(comment.getComments())) {
                    NewComment replyComment = comment.getComments().get(childPosition);
                    scb_comment_bar.setBookComment(null);
                    scb_comment_bar.setBookCommentReplyComment(comment, replyComment);
                    scb_comment_bar.setVisibility(View.VISIBLE);
                    scb_comment_bar.requestFocus();
                }
                Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
            }

            @Override
            public void onComment(View v, int position, BookComment bookComment) {
                scb_comment_bar.setBookComment(bookComment);
                scb_comment_bar.setVisibility(View.VISIBLE);
                scb_comment_bar.requestFocus();
                Utils.showSoftkeyboard(getActivity(), scb_comment_bar.getEditText());
            }

            @Override
            public void onEdit(int position, BookComment bookComment) {
                Intent in = new Intent(getActivity(), ModifyBookCommentActivity.class);
                ModifyBookCommentActivity.initArguments(in, position, "" + bookComment.id, bookComment.getContent());
                startActivity(in);
            }

            @Override
            public void onDel(int position, BookComment bookComment) {
                showDelDlg(position, bookComment);
            }
        });*/


        scb_comment_bar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        // 发送条 发送按钮点击监听
        /*scb_comment_bar.setOnSendButtonClickListener(new OnSendButtonClickListener() {
            @Override
            public void onSend(Object obj, String comment) {
                BookComment bookComment = (BookComment) obj;
                reqSendBookComment(bookComment, comment);
            }

            @Override
            public void onSend(Object obj, NewComment comment, String content) {
                // 发送comment的评论
                try {
                    BookComment bookComment = (BookComment) obj;
                    reqReplyComment(bookComment, comment, content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });*/

    }

    /**
     * 请求发送书摘的评论
     *
     * @param replyComment
     */
    /*private void reqReplyComment(final BookComment bookComment, final NewComment replyComment, final String content) {
        new RequestServerTask<SendCommentResponse>(SendCommentResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", replyComment.id);
                params.put("content", content);
                return HttpUtil.post(API.REPLY_COMMENT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SendCommentResponse result) {
                Utils.showToast("回复评论成功");

                // 添加数据 刷新界面
                List<NewComment> comments = bookComment.getComments();
                if (comments == null) {
                    comments = new ArrayList<NewComment>();
                }
                comments.add(result.data);
                if (mCommentAdapter != null) {
                    mCommentAdapter.notifyDataSetChanged();
                }

                if (mCommentMeAdapter != null) {
                    mCommentMeAdapter.notifyDataSetChanged();
                }
                Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                scb_comment_bar.setVisibility(View.GONE);
            }
        }.start();
    }*/

    /**
     * 收藏
     * @param comment
     */
    /*private void reqCollect(final BookComment comment) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", comment.id);
                return HttpUtil.post(API.COMMENT_COLLECT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                comment.collect_info.favorite = true;
                // 刷新
                if (mTypeMe) {
                    mCommentMeAdapter.notifyDataSetChanged();
                } else {
                    mCommentAdapter.notifyDataSetChanged();
                }
            }
        }.start();
    }*、

    /**
     * 取消点赞
     * @param comment
     */
    /*private void reqCancelPraise(final BookComment comment) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", comment.id);
                return HttpUtil.post(API.COMMENT_CANCEL_PRAISE, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                try {
                    comment.collect_info.plusone = false;
                    int praiseNum = Integer.parseInt(comment.getZan_num()) - 1;
                    comment.setZan_num(String.valueOf(praiseNum));
                } catch (Exception e) {
                    comment.setZan_num("0");
                } finally {
                    // 刷新
                    if (mTypeMe) {
                        mCommentMeAdapter.notifyDataSetChanged();
                    } else {
                        mCommentAdapter.notifyDataSetChanged();
                    }
                }
            }
        }.start();
    }*/

    /**
     * 点赞
     * @param comment
     */
    /*private void reqPraise(final BookComment comment) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", comment.id);
                return HttpUtil.post(API.COMMENT_PRAISE, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                try {
                    comment.collect_info.plusone = true;
                    int praiseNum = Integer.parseInt(comment.getZan_num()) + 1;
                    comment.setZan_num(String.valueOf(praiseNum));
                } catch (Exception e) {
                    comment.setZan_num("1");
                } finally {

                    // 刷新
                    if (mTypeMe) {
                        mCommentMeAdapter.notifyDataSetChanged();
                    } else {
                        mCommentAdapter.notifyDataSetChanged();
                    }
                }
            }
        }.start();
    }*/

    /**
     * 取消点赞
     * @param comment
     */
    /*private void reqCancelCollect(final BookComment comment) {
        new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.submit_loading)) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", comment.id);
                return HttpUtil.post(API.COMMENT_CANCEL_COLLECT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                // TODO: 16/3/31
                comment.collect_info.favorite = false;
                // 刷新
                if (mTypeMe) {
                    mCommentMeAdapter.notifyDataSetChanged();
                } else {
                    mCommentAdapter.notifyDataSetChanged();
                }
            }
        }.start();
    }*/

    /**
     * 删除书评
     *
     * @param bookComment
     */
    private void showDelDlg(final int position, final BookComment bookComment) {
        ColorDialog dialog = new ColorDialog(getActivity());
        dialog.setAnimationEnable(true);
        dialog.setTitle("删除书评");
        dialog.setContentText(getString(R.string.positive_to_add));
        dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                dialog.dismiss();
                new RequestServerTask<BaseResponse>(BaseResponse.class, getActivity(), getString(R.string.commit_pls_wait)) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("commentId", bookComment.id);
                        return HttpUtil.post(API.DELETE_COMMENT, params);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        dataList.remove(position);
                        mCommentMeAdapter.notifyDataSetChanged();
                        Utils.showToast(getActivity().getString(R.string.delete_success));
                    }
                }.start();
            }
        })
        .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                dialog.dismiss();
            }
        }).show();
    }

    /**
     * 请求发送书评的评论
     *
     * @param bookComment
     */
    /*private void reqSendBookComment(final BookComment bookComment, final String content) {
        new RequestServerTask<SendCommentResponse>(SendCommentResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("commentId", bookComment.id);
                params.put("content", content);
                return HttpUtil.post(API.REPLY_COMMENT, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SendCommentResponse result) {
                Utils.showToast("评论成功");

                // 添加数据 刷新界面
                List<NewComment> comments = (List<NewComment>) bookComment.getComments();
                if (comments == null) {
                    comments = new ArrayList<NewComment>();
                }
                comments.add(0, result.data);
                if (mCommentAdapter != null) {
                    mCommentAdapter.notifyDataSetChanged();
                }

                if (mCommentMeAdapter != null) {
                    mCommentMeAdapter.notifyDataSetChanged();
                }
                Utils.closeInputMethod(getActivity(), scb_comment_bar.getEditText());
                scb_comment_bar.setVisibility(View.GONE);
            }
        }.start();
    }*/

    private void setSelectToTop() {
        // LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        // layoutManager.scrollToPositionWithOffset(0, 0);
    }

    private boolean handleLoginClick() {
        boolean isLogin = PersistenceUtils.isLogin();
        Intent in = null;
        // 已登录 跳转到ProfileActivity
        if (isLogin) {
            return true;
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(getActivity(), NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            //getActivity().startActivity(in);
            return false;
        }
    }
}
